#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>

#include "comm.hpp"

#define Retry_Count 10   // 断线重连的次数

void Usage(const std::string &process)
{
    std::cout << "Usage: " << process << " server_ip server_port" << std::endl;
}

bool visitServer(std::string &serverip, uint16_t &serverport, int *cnt)
{
    // 1. 创建套接字（socket）
    std::string inbuffer;
    char service_list[1024];
    ssize_t m = 0;
    ssize_t n = 0;
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        return false;
    }
    bool ret = true;
    // 2. 要不要bind？必须要有Ip和Port, 需要bind，但是不需要用户显示的bind，client系统随机端口
    // 发起连接的时候，client会被OS自动进行本地绑定
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);                    // 本地字节序转换为网络字节序
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr); // 1. 字符串ip转化为4字节IP 2. 网络序列

    // 3. 网络连接（connect）
    n = connect(sockfd, CONV(&server), sizeof(server)); // 自动进行bind哦！
    if (n < 0)
    {
        std::cerr << "connect error" << std::endl;
        ret = false;
        goto END;
    }
    *cnt = 0;       // 连接次数重新置为零

    // 并没有向server一样，产生新的sockfd.未来我们就用connect成功的sockfd进行通信即可.
    while(true)
    {
        std::string inbuffer;
        std::cout << "Please Enter# ";
        getline(std::cin, inbuffer);

        n = write(sockfd, inbuffer.c_str(), inbuffer.size());
        if (n > 0)
        {
            char buffer[1024];
            m = read(sockfd, buffer, sizeof(buffer) - 1);
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << buffer << std::endl;
            }
            else if (m == 0)
            {
                return true;
            }
            else
            {
                ret = false;
                goto END;
            }
        }
        else
        {
            std::cout << "hello write Error" << std::endl;
            ret = false;
            goto END;
        }
    }
    END:
    close(sockfd);
    return ret;
}

// ./tcp_client serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);       // 字符串转化为整数

    int cnt = 1;
    while (cnt <= Retry_Count)
    {
        bool result = visitServer(serverip, serverport, &cnt);
        if (result)
        {
            break;
        }
        else
        {
            sleep(1);
            std::cout << "server offline, retrying..., count : " << cnt << std::endl;
            cnt++;
        }
    }

    if (cnt >= Retry_Count)
    {
        std::cout << "server offline" << std::endl;
    }
    return 0;
}